set more off

**betai and zstar are unknown so we need to simulate them given z

local J `1'
local sigma `2'
local sigmax `3'
local K `4'

reshape long x_ xout_ z_ epsilon_ , i(ID c alpha beta) j(altID)

rename x_ x
rename xout_ xout
rename z_ z
rename epsilon_ epsilon

*Create choice and open numbers
*Order choices by free utility
*Keep searching if:
*max_{k \in set of searched goods}  alpha*x_{k} + beta*z_{k} + epsilon_{k}   < alpha*x_{j+1} + beta*r + epsilon_{j+1}

*Loop through goods
*One variable is current best
*If current best exceeds benchmark for next good, stop and choose current best
*If current best is less than benchmark, keep going

*At the end of loop, need to tag open boxes and chosen good

gen FU = alpha*x+epsilon+xout*`K'
gen fullU = FU+beta*z

gsort ID -FU
by ID: gen newID = _n

gen id0=newID if altID==0
bys ID:egen sumid0=sum(id0)
replace newID=1 if sumid0~=1&altID==0
replace newID=newID+1 if sumid0~=1&altID~=0&newID<sumid0
gsort ID newID

forvalues x = 0/`J' {
			local z=`x'+1
by ID: gen FU_`x' = FU[`z']
by ID: gen U_`x' = fullU[`z']
}


preserve
keep ID c
duplicates drop
gen searchnum = floor((c)*runiform()+1)
*gen searchnum = floor(1.5+runiform())
*gen searchnum = floor(1.5+4*runiform())
*gen searchnum = floor(1.5+9*runiform())


tempfile numsearch
save `numsearch', replace
restore

merge m:1 ID using `numsearch'
assert _merge == 3
drop _merge
tab searchnum

gen open = 0
replace open = 1 if newID <= searchnum


gen tempU = fullU-(1-open)*1e20
bys ID: egen maxU = max(tempU)
gen chosen = (tempU == maxU)

bys ID: egen numchosen = sum(chosen)
egen maxchosen = max(numchosen)
local maxchosen = maxchosen
while(`maxchosen' != 1) {
drop numchosen maxchosen
replace tempU = tempU+.00001*uniform()
drop chosen
gen chosen = (tempU == maxU)
bys ID: egen numchosen = sum(chosen)
egen maxchosen = max(numchosen)
local maxchosen = maxchosen
}


drop numchosen maxchosen

